package com.java.base.io.netty;

import com.java.base.io.enter.ConsoleColorFont;
import com.java.base.io.enter.EnterLine;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

public class NettyClient {


    public void connect(String address, int port) {

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {

//                    ch.pipeline().addLast(new StringEncoder())
//                            .addLast(new StringDecoder())
                    ch.pipeline().addLast(new NettyClientChannelHandler());
                }
            });
            ChannelFuture channelFuture = bootstrap.connect(address, port).sync();

            enter(channelFuture.channel());

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }


    }

    static EnterLine enterLine = EnterLine.get(ConsoleColorFont.renders(" 发送> ", 1, 0, 7));

    public void enter(Channel channel) {

        while (channel.isOpen()) {
            String s = enterLine.readLine();
            if ("close".equals(s) || "stop".equals(s)) {
                channel.close();
                break;
            }
            channel.writeAndFlush(Unpooled.copiedBuffer(s.getBytes(StandardCharsets.UTF_8)));
            if ("stop server".equals(s)) {
                break;
            }
        }

    }

    public static class NettyClientChannelHandler extends ChannelInboundHandlerAdapter {


        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            String msg = MsgRender.msg("系统消息", ctx.channel().localAddress() + " 连接到服务器 " + ctx.channel().remoteAddress());
            enterLine.printMsg(msg);
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            String msg = MsgRender.msg("系统消息", ctx.channel().localAddress() + " 断开服务器 " + ctx.channel().remoteAddress());
            enterLine.printMsg(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String ms = ((ByteBuf) msg).toString(StandardCharsets.UTF_8);

            try {
                if (ms.substring(36).startsWith(ctx.channel().localAddress().toString())) {
                    ms = ms.substring(0, 32) + 2 + ms.substring(33);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            enterLine.printMsg(ms);
        }
    }


    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient();
        nettyClient.connect("127.0.0.1", NettyServer.port);
    }

}
